package com.accp.controller;

import com.accp.common.AjaxRtn;
import com.accp.model.User;
import com.accp.service.UserService;
import com.accp.util.RedisUtil;
import com.accp.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/8/16.
 */
@RestController
@Api(tags = "用户模块")
public class UserController {

    @Autowired
    private UserService userService;



    @RequestMapping(value="login",method= RequestMethod.POST)
    @ApiOperation(value = "前端用户登录",notes ="前端用户登录" )
    public AjaxRtn login(@RequestBody User user){
        Map<String,Object> result=new HashMap<>(16);
       User u=userService.selectByUser(user);
        if(u!=null){
            String token=StringUtil.getNonceStr();
            RedisUtil.set(u.getId()+"",token );
            result.put("userId",u.getId());
            result.put("token",token);
            return new AjaxRtn(true,"登陆成功",result);
        }else{
            return new AjaxRtn(false,"登陆失败","");
        }
    }

    @RequestMapping(value = "reg",method = RequestMethod.POST)
    @ApiOperation(value = "前端用户注册",notes ="前端用户注册")
    public AjaxRtn addUser(@RequestBody User user){
        Example example=new Example(User.class);
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("username",user.getUsername());
        List<User> users =userService.selectByExample(example);
        if(users.size()>0){
            return new AjaxRtn(false,"已经注册","");
        }else{
            userService.save(user);
            return new AjaxRtn(true,"注册成功","");
        }

    }


    /*
退出
 */
    @RequestMapping(value = "out",method = RequestMethod.POST)
    @ApiOperation(value = "前端用户退出",notes ="前端用户退出")
    public AjaxRtn out(@RequestBody String userId){
        RedisUtil.del(userId);
        return new AjaxRtn(true,"退出成功","");
    }
}
